var express = require("express");
var router = express.Router();
var queryWithPromise = require("../db/db").queryWithPromise;
var query_cat = require("../db/db").query_cat;

/* GET users listing. */
router.get("/getmenu", async function (req, res, next) {
  console.log(req.session.user_id);
  if (req.session.user_id) {
    try {
      // 获取用户对应的菜单项
      // res.send('respond with a resource');
      // 去后台获取菜单数据
      let user_id = req.session.user_id;
      let sql = "select * from user_role where user_id = ?";
      let menus = [];
      let { results } = await queryWithPromise(sql, [user_id]);
      let role_id = results[0].role_id; // 1
      // 根据角色 角色搜索 菜单 id
      let sql_menus = "select * from role_menu where role_id = ?";
      // res2
      let res_menus = await queryWithPromise(sql_menus, [role_id]);
      // 查询角色拥有的菜单的id
      let res2 = res_menus.results;
      for (let i = 0; i < res2.length; i++) {
        let cat_res = await query_cat(res2[i].cat_id);
        menus.push({
          cat_id: cat_res[0].cat_id,
          cat_name: cat_res[0].cat_name,
          cat_pid: cat_res[0].cat_pid,
        });
      }
      // query_cats(cat_ids);
      res.json({
        code: 1,
        data: menus,
      });
    } catch (err) {
      res.json({
        code: -1,
        msg: err,
      });
    }
  } else {
    res.json({
      code: -1,
      msg: "请先登录！",
    });
  }
});

module.exports = router;
